package lib

/* determine if is windows exclusive fullscreen */

import (
	"syscall"
	"unsafe"

	"golang.org/x/sys/windows"
)

const (
	GWL_STYLE = -16

	WS_BORDER     = 0x00800000
	WS_CAPTION    = 0x00C00000
	WS_THICKFRAME = 0x00040000

	SM_CXSCREEN = 0
	SM_CYSCREEN = 1
)

type RECT struct {
	Left, Top, Right, Bottom int32
}

var (
	user32                  = windows.NewLazySystemDLL("user32.dll")
	procGetForegroundWindow = user32.NewProc("GetForegroundWindow")
	procGetWindowRect       = user32.NewProc("GetWindowRect")
	procGetWindowLong       = user32.NewProc("GetWindowLongW")
	procGetSystemMetrics    = user32.NewProc("GetSystemMetrics")

	screenWidth  int32
	screenHeight int32
)

func getForegroundWindow() (hwnd syscall.Handle, err error) {
	r0, _, e1 := syscall.SyscallN(procGetForegroundWindow.Addr(), 0, 0, 0, 0)
	hwnd = syscall.Handle(r0)
	if hwnd == 0 {
		if e1 != 0 {
			err = error(e1)
		} else {
			err = syscall.EINVAL
		}
	}
	return
}

func getWindowRect(hwnd syscall.Handle, rect *RECT) (err error) {
	r0, _, e1 := syscall.Syscall(procGetWindowRect.Addr(), uintptr(2),
		uintptr(hwnd), uintptr(unsafe.Pointer(rect)), uintptr(0))
	if int(r0) == 0 {
		if e1 != 0 {
			err = error(e1)
		} else {
			err = syscall.EINVAL
		}
	}
	return
}

func getWindowProperty(hwnd syscall.Handle, nIndex int32) (value int32, err error) {
	r0, _, e1 := syscall.SyscallN(procGetWindowLong.Addr(), uintptr(hwnd), uintptr(nIndex))
	value = int32(r0)
	if value == 0 {
		if e1 != 0 {
			err = error(e1)
		} else {
			err = syscall.EINVAL
		}
	}
	return
}

func getSystemMetrics(nIndex int32) int32 {
	ret, _, _ := syscall.SyscallN(procGetSystemMetrics.Addr(), uintptr(nIndex))
	return int32(ret)
}

func Determine() (bool, error) {

	if screenWidth == 0 || screenHeight == 0 {
		screenWidth = getSystemMetrics(SM_CXSCREEN)
		screenHeight = getSystemMetrics(SM_CYSCREEN)
	}

	hwnd, err := getForegroundWindow()
	if err != nil {
		return false, err
	}

	var rect RECT
	err = getWindowRect(hwnd, &rect)
	if err != nil {
		return false, err
	}

	fullscreen := (rect.Left == 0 && rect.Top == 0 && rect.Right == screenWidth && rect.Bottom == screenHeight)
	if !fullscreen {
		return false, nil
	}

	style, err := getWindowProperty(hwnd, GWL_STYLE)
	if err != nil {
		return false, err
	}
	borderless := (style & (WS_BORDER | WS_CAPTION | WS_THICKFRAME)) == 0
	return borderless, nil
}
